<!--本组件是对businesscomponents/search的改造，向下兼容，扩展了展开搜索的功能-->
<template>
  <div class="custom-search-form">
    <el-form
      :inline="true"
      :model="formInline"
      :label-width="labelWidthStr"
      :label-position="labelPosition"
      class="el-form--inline filter-box"
    >
      <transition-group name="el-zoom-in-top">
        <el-form-item
          v-for="item in searchData"
          :key="item.key"
          :label="item.title"
          :label-width="item.labelWidth || labelWidthStr"
          :class="{badge: item.type === 'badge'}"
        >
          <div v-if="item.type === 'input'" class="divsss">
            <el-input v-model="formInline[item.key]" v-bind="item.attr" @focus="focuskey(item.key)"/>
          </div>

          <div v-if="item.type === 'select'">
            <el-select
              v-model="formInline[item.key]"
              v-bind="item.attr"
              :remote-method="remoteMethod"
              @focus="focuskey(item.key)"
              @change="changeKey($event, item.key)"
              @blur="blurKey(item.key)"
            >
              <el-option
                v-for="(items, index) in item.options"
                :title="items.label"
                :key="index"
                :label="items.label"
                :value="items.value"
              />
            </el-select>
          </div>
          <div v-if="item.type === 'mouth'">
            <el-date-picker
              v-model="formInline[item.key]"
              v-bind="item.attr"
              type="month"
              value-format="yyyy-MM"
            />
          </div>
          <div v-if="item.type === 'time'">
            <el-date-picker
              v-model="formInline[item.key]"
              v-bind="item.attr"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </div>

          <div v-if="item.type === 'radio'">
            <template>
              <el-radio
                v-for="items in item.options"
                :key="items.value"
                v-model="formInline[item.key]"
                :label="items.value"
                v-bind="item.attr"
                >{{ items.label }}</el-radio
              >
            </template>
          </div>

          <div v-if="item.type === 'badge'">
            <template>
              <el-badge
                v-for="(items, i) in item.options"
                :key="i"
                :class="{'badge-active': badgeKey === items.value}"
              >
                <el-button
                  class="badge-button"
                  size="small"
                  @click="changeStatus(item.key, items.value)"
                >
                  {{ items.label }}
                </el-button>
              </el-badge>
            </template>
          </div>

          <div v-if="item.type === 'cascader'">
            <el-cascader
              v-model="formInline[item.key]"
              :options="item.options"
              v-bind="item.attr"
              :props="item.optionProps"
            />
          </div>
          <div v-if="item.type === 'singleCascader'">
            <el-single-cascader
              v-model="formInline[item.key]"
              :options="item.options"
              v-bind="item.attr"
              :props="item.optionProps"
            />
          </div>

          <div v-if="item.type === 'rangeNumber'" class="rangeNumber">
            <el-input v-model="formInline[item.key[0]]" v-bind="item.attr" type="number" :min="0" @focus="focuskey(item.key[0])"/>
            ~
            <el-input v-model="formInline[item.key[1]]" v-bind="item.attr" type="number"  :min="formInline[item.key[0]]"  @focus="focuskey(item.key[1])"/>
          </div>
        </el-form-item>

      </transition-group>

      <el-form-item class="searchButtonList">
        <el-button icon="el-icon-search" class="submit" type="primary" @click.stop="search" v-if="queryReset"
          >查询</el-button>
        <el-button icon="el-icon-refresh-right" class="reset" @click.stop="reset" v-if="queryReset">重置</el-button>
           <el-row class="block-col-2" v-if="btnType === 'exportTable'">
          <el-col :span="12">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              导出表格
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(item,index) in tableText" :key="index" @click.native="exportTableItem(scope.row.id)" >{{item}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>

      </el-form-item>
    </el-form>
    <div v-if="showCollapse" class="collapse-button-wrapper">
      <el-button type="text" @click="collapse = !collapse">
        <span v-if="collapse"
          >展开详细查询 <i class="el-icon-arrow-down"
        /></span>
        <span v-else>收起详细查询 <i class="el-icon-arrow-up"/></span>
      </el-button>
    </div>
  </div>
</template>

<script>
import ElSingleCascader from '@components/el-single-cascader/src'
import {formatDate} from '@const/filter'
import {isObject} from 'lodash'
export default {
  name: 'Search',
  components: { ElSingleCascader },
  props: {
    data: {
      type: Array,
      default: () => []
    },
    // 自定义label-width长度
    labelWidth: {
      type: String,
      default: () => ''
    },
    labelPosition: {
      type: String,
      default: 'right'
    },
    queryReset:{
      type: Boolean,
      default: true
    },
    showCollapse: {
      type: Boolean,
      default: false
    },
    compactData: {
      // 收起搜索时的选项
      type: Array,
      default: () => []
    },
    btnType: {
      // 导出表格按钮
      type: String,
      default: ''
    },
  },
  data() {
    // 获取字段，设置默认为空

    let item = this.data
    let formInlineBox = {}
    // 用于badge 默认值
    let badgeKey = null
    item.forEach(item => {
      // 如果有默认值
      if (item.value) {
        formInlineBox[item.key] = item.value
        // 用于tab默认值
        if (item.type === 'badge') {
          badgeKey = item.value
        }
      } else {
        if (item.type === 'badge') {
          badgeKey = ''
        } else if (item.type === 'cascader') {
          formInlineBox[item.key] = []
        } else if (item.type === 'rangeNumber'){
          formInlineBox[item.key[0]] = null
          formInlineBox[item.key[1]] = null
        } else {
          formInlineBox[item.key] = null
        }
      }
    })
    return {
      // 弹框的内容
      tableText:["产品推广和学术拜访","货款回收管理","供货管理","使用信息管理","手术跟台支持","产品投诉与退换货","货物管理","产品培训教育活动","术前术后宣教活动"],
      tableVisible:false,
      // 用于判断弹出框中的选中的字段
      itemFlag:"",
      // 自定义表头长度
      labelWidthStr: this.labelWidth || '100px',
      // 内容数据
      formInline: {
        ...formInlineBox
      },
      // 用于badge
      badgeKey,
      collapse: true
    }
  },
  computed: {
    searchData() {
      return this.showCollapse && this.collapse ? this.compactData : this.data
    }
  },
  methods: {
    // 状态tab切换
    changeStatus(key, value) {
      this.formInline[key] = value
      this.badgeKey = value
      // 点击tab切换的时候直接查询列表
      this.search()
    },
    // 用于保存select为搜索下拉时使用
    changeKey(value, key) {
      this.$emit('changeKey', value, key)
    },
    // 用于保存select为搜索下拉时使用
    focuskey(key) {
      this.selectkey = key
      this.$emit('focuskey', this.selectkey)
    },
    // 用于保存select为搜索下拉时使用
    blurKey(key) {
      this.$emit('blurKey', key)
    },
    // 搜索下拉框返回值
    remoteMethod(query) {
      this.$emit('remoteMethod', query, this.selectkey)
    },
    // 点击搜索
    search() {
      console.log(this.formInline)
      // 表单数据
      let formData = {
        ...this.formInline
      }
      // 时间处理  为了点击提交不需要转换时间
      // 这里做了一个处理 在外层需要添加fieldname字段
      // fieldname为数组 必须两个值['开始时间字段',结束时间字段]
      this.searchData.forEach(item => {
        // 判断当前处理的时间一定是时间段
        if (item.type === 'time' && item.attr.type === 'daterange') {
          // 判断有没有选时间 且有fieldname字段
          if (formData[item.key] && item.fieldname) {
            // 开始时间
            formData[item.fieldname[0]] = formatDate(
              formData[item.key][0],
              'YYYY-MM-DD HH:mm:ss'
            )
            // 结束时间
            formData[item.fieldname[1]] = formatDate(
              formData[item.key][1],
              'YYYY-MM-DD HH:mm:ss'
            )
            // 删除多余的时间数组
            delete formData[item.key]
          }
        }
        // 处理单个时间
        if (item.type === 'time' && item.attr.type === 'date') {
          // 确定选了时间才处理
          if (formData[item.key]) {
            // 时间转换
            // 替换原来字段内容
            formData[item.key] = formatDate(
              formData[item.key],
              'YYYY-MM-DD HH:mm:ss'
            )
          }
        }
        // 对多类目处理-只返回一个ID
        if (item.type === 'cascader') {
          if (formData[item.key]) {
            if (isObject(formData[item.key])) {
              let index = formData[item.key].length
              if (index > 0) {
                formData[item.key] = formData[item.key][index - 1] + ''
              } else {
                formData[item.key] = null
              }
            }
          } else {
            formData[item.key] = null
          }
        }
      })

      // this.data.forEach(item => {
      //   if(item.type === 'rangeNumber'){
      //     if (formData[item.key[0]] && formData[item.key[1]] && Number(formData[item.key[0]]) >= Number(formData[item.key[1]])  ) {
      //       this.$message.warning(`${item.title}开始值不能大于等于结束值`)
      //     }
      //   }
      // })

      for (var i = 0 ,len = this.data.length; i<len ;i++){
        var temp = this.data[i]
        if(temp.type === 'rangeNumber'){
          if (formData[temp.key[0]] && formData[temp.key[1]] && Number(formData[temp.key[0]]) >= Number(formData[temp.key[1]])  ) {
            this.$message.warning(`${temp.title}开始值不能大于等于结束值`)
            return
          }
        }
      }
      this.$emit('searchForm', formData)
    },
    // 点击重置
    reset() {
      let arr = this.searchData
      let DefaultFormInlineBox = {}
      // 用于badge 默认值
      let badgeKey = null
      arr.forEach(item => {
        // 如果有默认值
        if (item.value) {
          DefaultFormInlineBox[item.key] = item.value
          // 用于tab默认值
          if (item.type === 'badge') {
            badgeKey = item.value
          }
        } else {
          DefaultFormInlineBox[item.key] = null
        }
      })
      this.formInline = DefaultFormInlineBox
      this.$emit('resetForm', this.formInline)
    },
    // 点击导出表格
    button(){
      this.tableVisible=!this.tableVisible;
    },
    exportTableItem(row){
      console.log(row);
      // this.itemFlag=index;
      // this.tableVisible=false
      // this.itemFlag=""
    }
  }
}
</script>

<style lang="less">
.custom-search-form {
  display: flex;

  .rangeNumber{
    .el-input{
      width: 45%;
      .el-input__inner{
        width: 98px;
      }
    }
  }
  .collapse-button-wrapper {
    flex: 0 0 120px;
  }

  .filter-box {
    flex: 1;

    .badge {
      display: block;
    }

    .daterange {
      width: 532px !important;
    }

    .el-badge {
      margin-right: 14px;
      line-height: 20px;
    }

    .badge-button {
      border: 0 !important;
      border-radius: 14px;
    }

    .el-input__inner {
      width: 211px;
    }

    .badge-active {
      .badge-button {
        background: #2371c5;
        color: #fff;
      }
    }

    .el-form-item {
      margin-bottom: 10px;
    }

    .el-form-item__label {
      padding-right: 10px;
    }
  }
.searchButtonList{
    >div{
      min-width: 305px;
    }
}

  .el-range-editor--medium .el-range-separator {
    line-height: 21px;
  }

  .el-range-editor--medium .el-range__icon,
  .el-range-editor--medium .el-range__close-icon {
    line-height: 21px;
  }
  .el-dropdown,.el-dropdown-link{
    display: block !important;
    width:100%;
  }
}
</style>
